#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>

int main(int argc,const char*argv[])
{
	if(argc!=3){printf("文件源缺失\n");return -1;}
	int p1=-1,p2=-1,top=0;
	char x;
	pid_t ret;
	ret=fork();
	if(ret>0)//父
	{
		printf("父进程：\n");
		if((p1=open(argv[1],O_RDONLY))==-1||(p2=open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,0664))==-1){perror("打开文件失败");return -1;}
		top=lseek(p1,0,2)/2;
		lseek(p1,0,0);
		lseek(p2,0,0);
		while(top--)
		{
			if(read(p1,&x,1)>0)
			{
				write(p2,&x,1);
				printf("%c",x);
			}

			else
			{
				perror("拷贝结束");
				break;
			}
		}
	close(p1);
	close(p2);
	}
	else if(ret==0)//子
	//else if(0)//子
	{
		printf("子进程：\n");
		if((p1=open(argv[1],O_RDONLY))==-1||(p2=open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,0664))==-1){perror("打开文件失败");return -1;}
		top=lseek(p1,0,2)/2;
		lseek(p1,top,0);
		lseek(p2,top,0);
		while(read(p1,&x,1)>0)
		{
			write(p2,&x,1);
			printf("%c",x);
		}
	close(p1);
	close(p2);
	exit(0);
	}
	else
	{
		perror("创建子进程失败：");
		return -1;
	}
	printf("回收完成：%d\n",wait(NULL));
	return 0;
}
